package cn.yuemouren.security.browser.session;

import cn.yuemouren.security.core.entity.SimpleResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: Timi
 * @Description: session策略类
 * @Date: 2020/6/28 13:46
 * @Version: v1.0
 */
public class AbstractSessionStrategy {

    private Logger logger = LoggerFactory.getLogger(getClass());

    //跳转的url
    private String destinationUrl;

    //重定向策略
    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    //跳转前是否创建新的session
    private boolean createNewSession = true;

    private ObjectMapper objectMapper = new ObjectMapper();

    public AbstractSessionStrategy(String invalidSessionUrl) {
        //检验失效路径是否合法
        Assert.isTrue(UrlUtils.isValidRedirectUrl(invalidSessionUrl),"url must start with '/' or with 'http(s)'");
        this.destinationUrl = invalidSessionUrl;
    }

    protected void onSessionInvalid(HttpServletRequest request, HttpServletResponse response) throws IOException {
        if(createNewSession){
            request.getSession();
        }

        String requestURI = request.getRequestURI();
        String targetUrl;
        if(StringUtils.endsWithIgnoreCase(requestURI,".html")){
            targetUrl = destinationUrl + ".html";
            logger.info("session失效跳转到:"+targetUrl);
            redirectStrategy.sendRedirect(request,response,targetUrl);
        } else {
            String message = "session已经失效";
            if(isConcurrency()){
                message += ",可能是并发登录导致的!";
            }
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(objectMapper.writeValueAsString(new SimpleResponse(message)));
        }
    }


    /**
     * session失效是否是并发导致的
     * @return
     */
    protected boolean isConcurrency() {
        return false;
    }

    /**
     * Determines whether a new session should be created before redirecting (to
     * avoid possible looping issues where the same session ID is sent with the
     * redirected request). Alternatively, ensure that the configured URL does
     * not pass through the {@code SessionManagementFilter}.
     *
     * @param createNewSession
     *            defaults to {@code true}.
     */
    public void setCreateNewSession(boolean createNewSession) {
        this.createNewSession = createNewSession;
    }
}
